package com.rc.saas.tenant.controller.tenant;

import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.tenant.TenantMenu;
import com.rc.saas.tenant.model.tenant.TenantMenuExample;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.tenant.TenantMenuService;
import com.rc.saas.tenant.service.tenant.TenantNavService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.tenant.TenantMenuVo;
import com.rc.saas.tenant.vo.tenant.TreeNodeModel;
import com.rc.saas.tenant.vo.tenant.TreeModel;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 导航菜单,这个功能不会开放给运营商
 */
@Controller
@RequestMapping("/tenant/menu")
public class TenantMenuController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(TenantMenuController.class);

    private String prefix = "/templates/tenant/menu";

    @Autowired
    private TenantNavService tenantNavService;

    @Autowired
    private TenantMenuService tenantMenuService;

    /**
     * 跳转首页列表
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String menu(Model model) {
        return prefix + "/menu";
    }

    /**
     * 返回列表数据
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<TenantMenu> list() {
        TenantMenuExample example = new TenantMenuExample();
        example.setOrderByClause("sort ASC");
        List<TenantMenu> menus = tenantMenuService.selectByExample(example);
        return menus;
    }

    /**
     * 跳转到增加页面
     * @param model
     * @param parentId
     * @return
     */
    @RequestMapping(value = "/add/{parentId}", method = RequestMethod.GET)
    public String add(Model model, @PathVariable("parentId") Long parentId) {
        model.addAttribute("parentId", parentId);
        if (parentId == null || parentId == 0) {
            model.addAttribute("parentName", "根目录");
        } else {
            model.addAttribute("parentName", tenantMenuService.selectByPrimaryKey(parentId).getMenuName());
        }
        return prefix + "/addMenu";
    }

    /**
     * 跳转到修改页面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(Model model, @PathVariable("id") Long id) {
        TenantMenu permission = tenantMenuService.selectByPrimaryKey(id);
        Long parentId = permission.getParentId();
        model.addAttribute("parentId", parentId);
        if (parentId == null || parentId == 0) {
            model.addAttribute("parentName", "根目录");
        } else {
            model.addAttribute("parentName", tenantMenuService.selectByPrimaryKey(parentId).getMenuName());
        }

        model.addAttribute("menu", permission);
        return prefix + "/editMenu";
    }

    /**
     * 保存
     * @param request
     * @param permission
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public TResponse save(HttpServletRequest request, TenantMenu permission) {
        try {
            //menuType权限类型:0菜单 1栏目 2功能
            if (permission.getTenantMenuId() != null) {
                tenantMenuService.updateByPrimaryKeySelective(permission);
            } else {
                //生成shiro的sys:menu:add授权格式,以在标签中使用
                //if (permission.getMenuType().equals("2") && StringUtils.isNotBlank(permission.getHref())) {
                //    //String path = "/tenant/menu/index";
                //    String o = "/";
                //    String r = ":";
                //    String rep = RegExUtils.replaceAll(permission.getHref(), o, r).substring(1);
                //    permission.setPermission(rep);
                //}

                tenantMenuService.insertSelective(permission);
            }

            return TResponse.SUCCESS();
        } catch (Exception e) {
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 删除
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public TResponse remove(HttpServletRequest request, Long id) {
        try {
            //先从下级菜单删除
            TenantMenuExample example = new TenantMenuExample();
            example.createCriteria().andParentIdEqualTo(id);
            List<TenantMenu> list = tenantMenuService.selectByExample(example);
            if (list != null && list.size() > 0) {
                return TResponse.FAIL("操作失败,请先将下级菜单删除");
            }

            tenantMenuService.deleteMenu(id);
        } catch (Exception e) {
            return TResponse.FAIL("操作失败");
        }

        return TResponse.SUCCESS();
    }

    /**
     * 功能授权
     */
    @RequestMapping(value = "/genPermission/{tenantMenuId}", method = RequestMethod.GET)
    public String genPermission(@PathVariable("tenantMenuId") Long tenantMenuId, Model model) {
        TenantMenu tenantMenu = tenantMenuService.selectByPrimaryKey(tenantMenuId);
        model.addAttribute("menu", tenantMenu);
        return prefix + "/genPermission";
    }

    /**
     * 解析文件
     */
    @ResponseBody
    @RequestMapping(value = "/scanPermission", method = RequestMethod.POST)
    public TResponse scanPermission(String fileNames) {
        //String folder="src/main/webapp/templates";
        String calssName = StringUtils.substringBefore(this.getClass().getSimpleName(), "Controller");

        try {
            StringBuilder sb = new StringBuilder();
            if (fileNames.indexOf(",") >= 0) {//多个文件
                String[] fileNameArray = fileNames.split(",");
                for (int i = 0; i < fileNameArray.length; i++) {
                    String fileName = fileNameArray[i].trim();
                    String ret = parseFile(calssName, fileName);
                    sb.append(ret);
                }
            } else {
                String ret = parseFile(calssName, fileNames);
                sb.append(ret);
            }

            return TResponse.SUCCESS_DATA(sb.toString());
        } catch (Exception e) {
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 保存
     */
    @ResponseBody
    @RequestMapping(value = "/savePermission", method = RequestMethod.POST)
    public TResponse savePermission(HttpServletRequest request, TenantMenuVo tenantMenuVo) {
        try {
            //增加:PlatformMenu_menu_add
            //查询:PlatformMenu_menu_reLoad
            String[] fileNameArray = tenantMenuVo.getResult().split("\r\n");
            for (int i = 0; i < fileNameArray.length; i++) {
                String fileName = fileNameArray[i].trim();

                String[] permissionNames = fileName.split(":");
                if (permissionNames.length > 0) {
                    String menuName = permissionNames[0].trim();
                    String permissionName = permissionNames[1].trim();

                    TenantMenu tenantMenu = tenantMenuService.selectMenuByPermission(tenantMenuVo.getTenantMenuId(), permissionName);
                    if (tenantMenu == null) {
                        TenantMenu newTenantMenu = new TenantMenu();
                        newTenantMenu.setParentId(tenantMenuVo.getTenantMenuId());
                        //权限类型: 0 目录 1 菜单 2 功能
                        newTenantMenu.setMenuType("2");
                        newTenantMenu.setMenuName(menuName);
                        newTenantMenu.setPermission(permissionName);

                        tenantMenuService.insertSelective(newTenantMenu);
                    }
                }
            }

            return TResponse.SUCCESS();
        } catch (Exception e) {
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 文件解析入口
     */
    private String parseFile(String calssName, String fileName) throws IOException {
        String extension = FilenameUtils.getExtension(fileName);
        if (extension.equals("jsp")) {
            return parseJspFile(calssName, fileName).toString();
        } else if (extension.equals("js")) {
            return parseJsFile(calssName, fileName).toString();
        } else {
            return "";
        }
    }

    /**
     * JSP文件解析
     */
    private StringBuilder parseJspFile(String calssName, String fileName) throws IOException {
        //从一个文件加载文档
        File input = new File(fileName);
        Document doc = Jsoup.parse(input, "UTF-8");

        String title = doc.title();
        Elements buttons = doc.select("button");

        logger.info("解析文件,:{},:{},:{}", fileName, title, buttons);

        //点号转下划线
        String o = ".";
        String r = "_";
        StringBuilder sb = new StringBuilder();
        for (Element button : buttons) {
            String text = button.text();
            String onclick = button.attr("onclick");
            //去掉括号
            onclick = StringUtils.substringBefore(onclick, "(");
            onclick = onclick.replace(o, r);

            sb.append(text);
            sb.append(":");
            sb.append(calssName + "_" + onclick);
            sb.append("\r\n");
        }
        logger.info("解析结果,:{},:{},:{}", fileName, title, buttons);

        return sb;
    }

    /**
     * JS文件解析
     */
    private StringBuilder parseJsFile(String calssName, String fileName) throws IOException {
        //从一个文件加载文档
        File input = new File(fileName);
        Document doc = Jsoup.parse(input, "UTF-8");

        String title = doc.title();
        Elements buttons = doc.select("a[onclick]");
        logger.info("解析文件,:{},:{},:{}", fileName, title, buttons);

        //点号转下划线
        String o = ".";
        String r = "_";
        StringBuilder sb = new StringBuilder();
        for (Element button : buttons) {
            String text = button.text();
            String onclick = button.attr("onclick");
            //去掉括号
            onclick = StringUtils.substringBefore(onclick, "(");
            onclick = onclick.replace(o, r);

            sb.append(text);
            sb.append(":");
            sb.append(calssName + "_" + onclick);
            sb.append("\r\n");
        }
        logger.info("解析结果,:{},:{},:{}", fileName, title, buttons);

        return sb;
    }

    /**
     * 创建整棵树
     * @return
     */
    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    @ResponseBody
    public TreeModel<TreeNodeModel> tree() {
        TenantUser user = ShiroUtils.getSessionUser();
        TreeModel<TreeNodeModel> tree = tenantNavService.buildTree(user);
        return tree;
    }

    /**
     * 根据角色ID创建树
     * @param roleId
     * @return
     */
    @RequestMapping(value = "/tree/{roleId}", method = RequestMethod.GET)
    @ResponseBody
    public TreeModel<TreeNodeModel> tree(@PathVariable("roleId") Long roleId) {
        TenantUser user = ShiroUtils.getSessionUser();
        TreeModel<TreeNodeModel> tree = tenantNavService.buildTree(user, roleId);
        return tree;
    }

    /**
     * 跳转首页列表
     * @param model
     * @return
     */
    @RequestMapping(value = "/tenantMenu", method = RequestMethod.GET)
    public String tenantMenu(Model model) {
        return prefix + "/tenantMenu";
    }
}
